/**
 * WeeShop 声明
 * ===========================================================
 * 网站： https://www.darlang.com
 * 标题： ECShop 小程序「weeshop 」- 基于 ECShop 为后台系统开发的非官方微信商城小程序
 * 链接： https://www.darlang.com/?p=709
 * 说明： 源码已开源并遵循 Apache 2.0 协议，你有权利进行任何修改，但请保留出处，请不要删除该注释。
 * ==========================================================
 * Copyright 2019 darlang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ===========================================================
 */

// index.js
import { PNT, setNavBarTitle, request, showToast, pushPagePath, formatTime, scrollLoadList, checkMobile} from "../../../utils/utils";
import { GetDoRealName, GetSendVcode} from '../../../utils/apis';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    recommendLst: '',
    recommendInfo: [],
    wxaCodeStatus: true,
    page:0,
    pages: {
      page: 1,
      size: 10,
      total: 10,
      done: false,
      loading: false
    },
    x:'http://www.donglongshangshi.com/mobile/public/img/idimg_one.jpg',
    y:'http://www.donglongshangshi.com/mobile/public/img/idimg_two.jpg',
    flag:true,

    phone: '',
    code: '',
    second: 60,
    flag: true,
    sms: '获取短信验证码',
    code: true,
    type:'real',
    real:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    setNavBarTitle(PNT.member.account);
    this.loginModal = this.selectComponent("#login-modal");
    if(!this.loginModal.check()){
      return false;
    }
    var info = wx.getStorageSync('userInfo');
    this.setData({
      info:info,
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 登录回调
   * @author darlang
   */
  loginCallback(cb) {
    if (cb.detail.type === 'success') {
      // this.getRecommendList();
      this.getRecommendInfo();
    }
  },

  phone(e){
    this.setData({
      phone:e.detail.value
    })
  },
  //获取验证码

  sms: function (e) {
    var that = this;
    if (!this.data.code) {
      var sms = that.data.sms;
      wx.showToast({
        title: sms,
        icon: 'none'
      })
      return;
    }
    that.setData({
      code: false
    })
    var type = this.data.type;
    var phone = this.data.phone;
    if (!checkMobile(phone)){
      wx.showToast({
        title: '手机格式不正确',
        icon:'none'
      })
      return;
    }
    // phone = '17310606312';
    var user_id = this.data.info.user_id;
    var data = { type, phone, user_id };
    GetSendVcode(data).then(res => {
      if (res.error_code == 10000) {
        wx.showToast({
          title: '验证码发送成功',
        })
        that.time()
      } else {
        this.setData({
          code: true,
        })
      }
    }).catch(function (reason) {
      wx.showToast({
        title: '服务器忙',
      })
      that.onLoad();
    })
  },
  time: function (e) {
    var that = this;
    var time = 120;
    var inter = setInterval(function () {
      time--;
      that.setData({
        sms: "请" + time + "秒后再发"
      })
      if (time == 0) {
        that.setData({
          sms: '获取短信验证码',
          code: true,
        })
        clearInterval(inter)
      }
    }, 1000)
  },

  //上传身份证照片
  chooseImg(e){
    var self = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: 'https://www.donglongshangshi.com//wechatapi/index.php/wechatapi/index/chooseImg',  //此处换上你的接口地址
          filePath: tempFilePaths[0],
          name: 'img',
          header: {
            "Content-Type": "multipart/form-data",
            'accept': 'application/json',
            'Authorization': 'Bearer ..' //若有token，此处换上你的token，没有的话省略
          },
          formData: {
            type: e.currentTarget.dataset.type //其他额外的formdata，可不写
          },
          success: function (res) {
            var data = JSON.parse(res.data);
            if(data.error_code == 10000){
              console.log(data.data)
              if(data.type == 'x'){
                self.setData({
                  x:data.data,
                })
              }else{
                self.setData({
                  y: data.data,
                })
              }
            }
            console.log(data);
          },
          fail: function (res) {
            console.log('fail');

          },
        })
      }
    })
  },
  setParam:function(that,e){
    that.setData(e)
  },

  //提交表单
  formSubmit(e){
    console.log(e)
    var that = this;
    var flag = this.data.flag;
    if(!flag){
      wx.showLoading({
        title: '数据提交中...',
      })
      setTimeout(function(){
        wx.hideLoading();
      },2000)
      return;
    }
    flag = false;
    that.setParam(that, { flag: flag })
    //身份证正则
    var idcardcheck =  /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
    //银行卡号正则
    var bankcardcheck = /^([1-9]{1})(\d{14}|\d{18})$/;
    //手机号正则
    var phonecheck = /^1[3456789]\d{9}$/;
    //数字正则
    var vcodecheck = /^[0-9]*$/;

    var imgx = that.data.x;
    var imgy = that.data.y;

    if(!e.detail.value.realname){
      wx.showToast({
        title: '请输入真实姓名',
        icon: 'none'
      })
      flag = true;
      that.setParam(that,{flag:flag})
      return;
    }
    if (!e.detail.value.iDcard || !idcardcheck.test(e.detail.value.iDcard)){
      wx.showToast({
        title: '请输入合法身份证号',
        icon: 'none'
      })
      flag = true;
      that.setParam(that, { flag: flag })
      return;
    }
    if (!imgx || imgx == undefined) {
      wx.showToast({
        title: '请上传身份证正面照',
        icon:'none'
      })
      flag = true;
      that.setParam(that, { flag: flag })
      return;
    }
    if (!imgy) {
      wx.showToast({
        title: '请上传身份证反面照',
        icon: 'none'
      })
      flag = true;
      that.setParam(that, { flag: flag })
      return;
    }
    if (!e.detail.value.bank) {
      wx.showToast({
        title: '请输入银行',
        icon: 'none'
      })
      flag = true;
      that.setParam(that, { flag: flag })
      return;
    }
    if (!e.detail.value.bankCard || !bankcardcheck.test(e.detail.value.bankCard)) {
      wx.showToast({
        title: '请输入合法银行卡号',
        icon: 'none'
      })
      flag = true;
      that.setParam(that, { flag: flag })
      return;
    }
    if (!e.detail.value.phone || !phonecheck.test(e.detail.value.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      flag = true;
      that.setParam(that, { flag: flag })
      return;
    }
    if (!e.detail.value.vcode || !vcodecheck.test(e.detail.value.vcode)) {
      wx.showToast({
        title: '请输入合法验证码',
        icon: 'none'
      })
      flag = true;
      that.setParam(that, { flag: flag })
      return;
    }
    var info = wx.getStorageSync('userInfo');
    var data = {};
    data.user_id = info.user_id;
    data.real_name = e.detail.value.realname;
    data.self_num = e.detail.value.iDcard;
    data.front_of_id_card = this.data.x;
    data.reverse_of_id_card = this.data.y;
    data.bank_name = e.detail.value.bank;
    data.bank_card = e.detail.value.bankCard;
    data.bank_mobile = e.detail.value.phone;
    data.vcode = e.detail.value.vcode;
    data.type = this.data.type;
    GetDoRealName(data).then(res=>{
      console.log(res)
      this.setData({
        flag:true,
      })
      if(res.error_code == 10000){
        wx.showToast({
          title: res.msg,
          icon:'none'
        })
        setTimeout(function(){
          wx.navigateBack({
            delta:1,
          })
        },1500)
      }else{
        showToast(res.msg,'warning')
      }
    })





    console.log(e)

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#F6344D",
      animation: {
        duration: 300,
        timingFunc: "linear"
      }
    });
    // this.getWxQrcode();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const u = wx.getStorageSync('userInfo') || '';
    if (!u) {
      showToast('登录异常,分享失败');
      return false;
    }
    var shareName = this.data.siteInfo.name || '' ;
    var imgUrl = '/images/default_activity-'+parseInt(Math.random()*2)+'.png';
    var shareLink = '/pages/index/index?inviteCode='+(u.id || '');
    return {
      title: shareName || PNT.default,
      imageUrl: imgUrl || '/images/default_image.png',
      path: shareLink,
      success() {},
      fail() {},
      complete() {}
    };
  }
});